const http = require('http')
const ejs = require('ejs')
const querystring = require('querystring')
const { MongoClient, ObjectId } = require('mongodb')
const app = require('./module/route')
const url = require('url')

const dburl = 'mongodb://pan:123456@127.0.0.1:27017/limi'

// 注册web服务
http.createServer(app).listen(3000);

// 配置路由
app.get('/', (req, res) => {
  MongoClient.connect(dburl, { useUnifiedTopology: true }, (err, client) => {
    if (err) {
      console.log(err)
      return
    }
    let db = client.db()
    db.collection('user').find({}).toArray((err, result) => {
      if (err) {
        console.log(err)
        return
      }
      client.close()
      ejs.renderFile('./views/index.ejs', {
        list: result
      }, (err, data) => {
        res.send(data)
      })
    })
  })

})

app.get('/toAdd', (req, res) => {
  ejs.renderFile('./views/form.ejs', {
    title: '新增',
    msg: '',
    user: { _id: '', name: '', age: '', sex: '' }
  }, (err, data) => {
    res.send(data)
  })
})

app.post('/save', (req, res) => {
  MongoClient.connect(dburl, { useUnifiedTopology: true }, (err, client) => {
    if (err) {
      console.log(err)
      return
    }
    let db = client.db()
    const body = querystring.parse(req.body)
    // 更新数据
    if (body._id) {
      db.collection('user').updateOne({ _id: ObjectId(body._id) },
        { $set: { name: body.name, age: body.age, sex: body.sex } }, (err, result) => {
          if (err) {
            console.log(err)
            return
          }
          client.close()
          ejs.renderFile('./views/form.ejs', {
            title: '更新',
            msg: '数据更新成功',
            user: { ...body }
          }, (err, data) => {
            res.send(data)
          })
        })
    } else { // 新增数据
      db.collection('user').insertOne({ ...body }, (err, result) => {
        if (err) {
          console.log(err)
          return
        }
        client.close()
        ejs.renderFile('./views/form.ejs', {
          title: '新增',
          msg: '新增数据成功',
          user: { _id: '', name: '', age: '', sex: '' }
        }, (err, data) => {
          res.send(data)
        })
      })
    }

  })

})

app.get('/toUpdate', (req, res) => {
  MongoClient.connect(dburl, { useUnifiedTopology: true }, (err, client) => {
    if (err) {
      console.log(err)
      return
    }
    let db = client.db()
    const query = url.parse(req.url, true).query
    db.collection('user').findOne({ _id: ObjectId(query.id) }, (err, result) => {
      if (err) {
        console.log(err)
        return
      }
      client.close()
      ejs.renderFile('./views/form.ejs', {
        title: '更新',
        msg: '',
        user: { ...result }
      }, (err, data) => {
        res.send(data)
      })
    })
  })
})

app.get('/delete', (req, res) => {
  MongoClient.connect(dburl, { useUnifiedTopology: true }, (err, client) => {
    if (err) {
      console.log(err)
      return
    }
    let db = client.db()
    const query = url.parse(req.url, true).query
    db.collection('user').deleteOne({ _id: ObjectId(query.id) }, (err, result) => {
      if (err) {
        console.log(err)
        return
      }
      client.close()
      res.send('数据删除成功')
    })
  })
})

console.log('Server running at http://127.0.0.1:3000/');